package com.ts.code.creator.creator.impl;

import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiElementFinder;
import com.intellij.psi.PsiJavaCodeReferenceElement;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.ts.code.creator.enums.CreateFileEnum;
import com.ts.code.creator.express.ExpressContext;
import com.ts.code.creator.express.ExpressUtil;
import com.ts.code.creator.util.CreateCodeContext;
import com.ts.code.creator.util.StringUtil;

/**
 * 聚合层 controller
 */
public class AdminControllerCreator extends AbstractCodeCreator {

    public AdminControllerCreator(CreateCodeContext context) {
        super(context);
    }

    @Override
    protected CreateFileEnum createFileEnum() {
        return CreateFileEnum.ADMIN_CONTROLLER;
    }

    @Override
    public void doCreate() {
        String javaFile = classFileSearch.adminController();
        addMethod(javaFile, adminController(context));
    }

    private String adminController(CreateCodeContext context) {
        String text = remark("param") +
                "    @PostMapping(\"${postUrl}\")\n" +
                "    Result<${returnClass}> ${methodName}(${paramStr}) {\n" +
                "        return Result.success(${entityNameLower}Service.${methodName}(${paramName}));\n" +
                "    }";

        String postUrl = StringUtil.nameToUrl(context.getMethodName());

        // 参数
        String paramStr = adminParam();
        if (StringUtil.isNotBlank(paramStr)) {
            paramStr = "@RequestBody @Valid " + paramStr;
        }

        ExpressContext expressContext = new ExpressContext();
        expressContext.put(context);
        expressContext.put("returnClass", adminVO());
        expressContext.put("postUrl", postUrl);
        expressContext.put("paramStr", paramStr);
        expressContext.put("paramName", StringUtil.isNotBlank(adminParam()) ? "param" : "");
        expressContext.put("entityNameLower", StringUtil.firstLower(context.getEntityName()));
        return ExpressUtil.eval(text, expressContext);
    }

}
